<template>
  <!--养殖项目  -->
  <el-form ref="formRef" :model="dynamicValidateForm" class="demo-dynamic">
    <el-row :gutter="24">
      <el-col :span="0"></el-col>
      <el-col :span="24">
        <el-button type="text" @click.prevent="addDomain()">
          <el-icon>
            <Plus />
          </el-icon>
          <span>若有养殖项目点击此处进行添加</span>
        </el-button>
      </el-col>
    </el-row>
    <el-row
      v-for="(domain, index) in dynamicValidateForm.domains"
      :gutter="24"
      :key="domain.key"
      aria-label="121"
    >
      <el-col :span="10">
        <el-form-item
          :label="'养殖项目(' + (index + 1) + ')'"
          :prop="'domains.' + index + '.farm'"
          :rules="{
            required: true,
            message: '请选择养殖项目！',
            trigger: 'blur',
          }"
        >
          <el-select
            v-model="domain.farm"
            placeholder="请选择养殖项目"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in dict.type.pea_farm_pro"
              :key="index"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="10">
        <el-form-item
          :label="'年产量（千克）'"
          :prop="'domains.' + index + '.yearOp'"
          :rules="{
            required: true,
            message: '请输入年产量！',
            trigger: 'blur',
          }"
        >
          <el-input v-model="domain.yearOp" show-word-limit maxlength="10" placeholder="请输入年产量" />
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-button @click.prevent="removeDomain(domain)" style="margin-top: 30px;">
          <el-icon>
            <Minus />
          </el-icon>
        </el-button>
      </el-col>
    </el-row>

    <el-form-item>
      <el-button @click="resetForm(formRef)" v-show="dynamicValidateForm.domains.length != 0">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from "vue";
import type { FormInstance } from "element-plus";
import { farmPro } from "@/views/credit/peasants/pea-message/type";

const formRef = ref<FormInstance>();
const dynamicValidateForm = reactive<{
  domains: DomainItem[]
}>({
  domains: []
});

interface DomainItem extends farmPro {
  key: number;
  farm: string; // 养殖项目
  yearOp: string; // 年产量
}


let props = defineProps(["farming", "hzId"]);
let $emit = defineEmits(["update:farming"]);

// 移除
const removeDomain = (item: DomainItem) => {
  // 克隆一个新的数组
  const index = dynamicValidateForm.domains.indexOf(item);
  if (index !== -1) {
    dynamicValidateForm.domains.splice(index, 1);
    // 修改之后再次进行赋值
    $emit("update:farming", dynamicValidateForm.domains);
  }
};

// 新增
const addDomain = () => {
  // 向新数组中添加元素
  dynamicValidateForm.domains.push({
    key: Date.now(),
    farm: "", // 养殖项目
    yearOp: "" // 年产量
  });
  $emit("update:farming", dynamicValidateForm.domains);
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dynamicValidateForm.domains.forEach((item) => {
    item['farm'] = "";
    item['yearOp'] = "";
  })
  $emit("update:farming", dynamicValidateForm.domains);
};

const subFarm = () => {
  // 创建一个 Promise 对象
  return new Promise((resolve, reject) => {
    formRef.value.validate((valid, fields) => {
      // 进行
      if (!formRef) reject("养殖表单还有未填写字段，请填写！");
      if (valid) {
        resolve(true);
      } else {
        reject("养殖表单还有未填写字段，请填写！");
      }
    });
  });
};

// 监听id是否发生变化，变了从新进行赋值操作
watch(
  () => props.hzId,
  () => {
    dynamicValidateForm.domains = [...props.farming];
  }
);

// 保存数据的同步
watch(
  () => dynamicValidateForm.domains,
  () => {
    $emit("update:farming", dynamicValidateForm.domains);
  }
);



// update:farming
onMounted(() => {
  // 进行赋值操作
  dynamicValidateForm.domains = [...props.farming];
});

// 清空
const removeAll = () => {
  dynamicValidateForm.domains = [];
  $emit("update:farming", dynamicValidateForm.domains)
}

defineExpose({
  subFarm,
  removeAll
});
</script>

<script lang="ts">
export default {
  dicts: ["pea_farm_pro"]
};
</script>

<style lang="scss" scoped></style>
